/**
 * @name SignUp
 * @author darcrand
 * @desc 注册页面
 * @description
 */

import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'
import { Button, Form, Input, Radio, Tooltip } from 'antd'
import { QuestionCircleOutlined } from '@ant-design/icons'
import { AvatarUploader, FormWrapper } from '@/components'
import { apiSingleFileUpload, apiGetGenders } from '@/apis/common'

import logoColor from '@/assets/images/afaire-logo-color-128.png'

import styles from './styles.module.less'

@inject('user')
@observer
class SignUp extends Component {
  state = { genderOptions: [] }
  refForm = React.createRef()

  componentDidMount() {
    this.init()
  }

  init = async () => {
    const genderOptions = await apiGetGenders()
    this.setState({ genderOptions })
    this.refForm.current.setFieldsValue({ gender: genderOptions[0].value })
  }

  onFormFinish = async (values = {}) => {
    try {
      const { imgFile, confirm, nickname, ...rest } = values
      let imageUrl = ''
      let finalNickname = nickname

      if (typeof imgFile === 'object') {
        imageUrl = await apiSingleFileUpload(imgFile)
      }

      if (!finalNickname || !finalNickname.trim()) {
        // 如果不指定昵称,则使用邮箱地址的名称部分作为昵称
        finalNickname = rest.username.split('@')[0]
      }

      await this.props.user.signUp({ avatar: imageUrl, nickname: finalNickname, ...rest })
      this.props.history.replace('/')
    } catch (err) {
      console.error('注册失败', err)
    }
  }

  render() {
    return (
      <div className={styles.container}>
        <img src={logoColor} alt='afaire' className={styles.logo} />
        <h1 className={styles.title}>Sign Up</h1>

        <FormWrapper>
          <Form ref={this.refForm} {...FormWrapper.FORM_ITEM_LAYOUT} onFinish={this.onFormFinish}>
            <Form.Item
              label='Email'
              name='username'
              rules={[
                { required: true, message: 'Please input your username!' },
                { type: 'email', message: 'You should input a Email!' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name='password'
              label='Password'
              rules={[
                {
                  required: true,
                  message: 'Please input your password!',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name='confirm'
              label='Confirm Password'
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: 'Please confirm your password!',
                },
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject('The two passwords that you entered do not match!')
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              label={
                <span>
                  Nickname&nbsp;
                  <Tooltip title='What do you want others to call you?'>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              }
              name='nickname'
            >
              <Input />
            </Form.Item>

            <Form.Item label='Gender' name='gender'>
              <Radio.Group options={this.state.genderOptions} />
            </Form.Item>

            <Form.Item label='Description' name='desc'>
              <Input />
            </Form.Item>
            <Form.Item label='Curriculum Vitae' name='cv'>
              <Input.TextArea rows={5} />
            </Form.Item>

            <Form.Item label='Avatar' name='imgFile'>
              <AvatarUploader />
            </Form.Item>

            <Form.Item {...FormWrapper.TAIL_FORM_LAYOUT}>
              <Button type='primary' htmlType='submit' size='large'>
                sign up
              </Button>
            </Form.Item>
          </Form>
        </FormWrapper>
      </div>
    )
  }
}

export default SignUp
